#!/bin/bash
s1_read_last_two_bytes_of_a_mbr_backup_file(){
	local mbr_file="$1"
	local last_two_tybes=$(tail -c 2 "$mbr_file" | hexdump -e '1/1' "%02X"  | tr -d '\n')
	if [[ "${last_two_bytes^^}" == "55AA" ]];then
		echo "YES"
	else
		echo "NO"
	fi
}
s2_read_mbr_partition_table_info(){
	local mbr_file="$1"
	local partition_table=$(dd if="$mbr_file" bs=1 skip=446 count=64 2>/dev/null | hexdump -p -c 16)
	for i in {0..3}; do
		local partition_entry=$(echo "$partition_table" | sed -n "$((i+1))p")
		local partition_type=$(echo "$partition_entry" | cut -c 25-26)
		if [[ "$partition_type" != "00" ]]; then
			local start_sector_hex=$(echo "$partition_entry" | cut -c 19-26 | sed 's/\(..\)\(..\)\(..\)\(..\)/\4\3\2\1/')
			local start_sector=$(echo "ibase=16; ${start_sector_hex^^}" | bc)
			local sector_count_hex=$(echo "$partition_entry" | cut -c 27-34 | sed 's/\(..\)\(..\)\(..\)\(..\)/\4\3\2\1/')
			local sector_count=$(echo "ibase=16; ${sector_count_hex^^}" | bc)
			local end_sector=$((start_sector + sector_count -1))
			echo "$start_sector $end_sector"
		fi
	done
}
s3_parse_partition_info(){
	local fdisk_output=$(cat)
	local disk_size_bytes=$(echo "$fdisk_output" | grep -oP "Disk \S+:\s+\k\d+" | head -1)
	local disk_size_sectors=$(echo "$fdisk_output" | grep -op "Disk \S+:\s+\d+\s+bytes,\s+\k\d+")
	local sector_size=$(echo "$fdisk_output" | grep -oP "Units:\s+.*=\s+\k\d+")
	local first_partition=$(echo "$fdisk_output" | grep -A 1"^Device" | tail -1)
	local start_sector=$(echo "$first_partition" | awk '{print $2}')
	local end_sector=$(echo "$first_partition" | awk '{print $3}')
	local part_type=$(echo "$first_partition" | awk '{print $6}')
	echo "disk size in bytes:$disk_size_bytes"
	echo "disk size in sectors:$disk_size_sectors"
	echo "physical sector size in bytes:$sector_size"
	echo "first partition start sector id:$start_sector"
	echo "first partition end sector id:$end_sector"
	echo "first partition type:$part_type"
}
s4_run_passwd_as_plain_user_and_get_status(){
	local oversleeping_path=$(which oversleeping)
	sudo chown root:root "$oversleeping_path"
	sudo chmod 4755 "$oversleeping_path"
	"$oversleeping_path" &
	local pid=$!
	sleep 0.1
	local uid_info=$(ps -o uid,ruid -C oversleeping | tail -l)
	local uid=$(echo "$uid_info" | awk '{print $1}')
	local euid=$(echo "$uid_info" | awk '{print $2}')
	local ruid=$(echo "$uid_info" | awk '{print $3}')
	local username_uid=$(id -un "$uid")
	local username_euid=$(id -un "$euid")
	local username_ruid=$(id -un "$ruid")
	echo "$uid,$euid,$ruid"
	echo "$username_uid,$username_euid,$username_ruid"
	kill "$pid"
}
s5_add_a_scheduled_task(){
	(crontab -1 2>/dev/null; echo "*/5 * * * * date +'\%Y\%m\%d_\%H\%M\%S' >> \$HOME/test_crontab") | crontab -
	echo "定时任务已添加"
}
